<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        #app2 {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
        }

        .close-btn:hover {
            background-color: #f5f5f5;
        }

        .required {
            color: #e53935;
        }

        .no-data {
            text-align: center;
            padding: 40px 0;
            color: #999;
        }

        /* 权限树样式 */
        .permission-tree {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            background-color: #fafafa;
        }

        .permission-tree ul {
            list-style: none;
            padding-left: 20px;
        }

        .permission-tree li {
            margin: 8px 0;
            display: flex;
            align-items: center;
        }

        .permission-tree input[type="checkbox"] {
            margin-right: 8px;
        }

        .permission-tree .folder-icon {
            margin-right: 8px;
            color: #ff9800;
        }

        .permission-tree .page-icon {
            margin-right: 8px;
            color: #2196f3;
        }
    </style>
</head>
<body>

<div id="app2">
    <!-- 主内容区 -->
    <div class="main-content">


        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">角色查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="roleName">角色名称</label>
                            <input type="text" v-model="searchForm.roleName" class="form-control"
                                   placeholder="请输入角色名称">
                        </div>
                        <div class="form-group col-3">
                            <label for="description">描述</label>
                            <input type="text" v-model="searchForm.roleDescription" class="form-control"
                                   placeholder="请输入描述">
                        </div>
                        <div class="form-group col-3">
                            <label>&nbsp;</label>
                            <div class="search-buttons">
                                <button type="submit" class="btn btn-primary" style="margin-right: 10px;">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                                <button type="button" class="btn btn-success" @click="openModal('添加角色')">
                                    <i class="fas fa-plus"></i> 添加角色
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 角色列表 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">角色列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table>
                            <!-- 表格头部 -->
                            <thead>
                            <tr>
                                <th>角色ID</th>
                                <th>角色名称</th>
                                <th>描述</th>
                                <th>状态</th>
                                <th>更新时间</th>
                                <th style="width: 320px; text-align: center;">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.roleId">
                                <td>{{ item.roleId }}</td>
                                <td>{{ item.roleName }}</td>
                                <td>{{ item.roleDescription }}</td>
                                <td>
                                    <span v-if="item.status === 1" class="status-active">启用</span>
                                    <span v-else class="status-inactive">禁用</span>
                                </td>
                                <td>{{ formatDateTime(item.updateTime || item.createTime) }}</td>
                                <!-- 在表格的操作列中恢复完整的操作按钮 -->
                                <td style="text-align: center;">
                                    <div class="action-buttons" style="flex-direction: row !important;">
                                        <button class="btn btn-sm btn-primary" @click="handleEdit(item)">
                                            <i class="fas fa-edit"></i> 编辑
                                        </button>
                                        <button class="btn btn-sm btn-primary" @click="handlePermission(item)">
                                            <i class="fas fa-key"></i> 权限
                                        </button>
                                        <button class="btn btn-sm btn-danger" @click="handleDelete(item.roleId)">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <!-- 无数据提示 -->
                        <div v-if="tableData.length === 0" class="no-data">
                            <p>暂无数据</p>
                        </div>
                    </div>

                    <!-- 分页区域 -->
                    <div class="pagination" v-if="totalItems > 0"
                         style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="isModalVisible" class="modal-overlay" @click.self="closeModal">
        <div class="modal">
            <div class="modal-header">
                <h3>{{ currentModalTitle }}</h3>
                <button class="close-btn" @click="closeModal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="editRoleName">角色名称 <span class="required">*</span></label>
                        <input type="text" class="form-control" id="editRoleName" v-model="formData.roleName"
                               placeholder="请输入角色名称" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="editStatus">角色状态</label>
                        <select class="form-control" id="editStatus" v-model="formData.status">
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="editDescription">描述</label>
                        <input type="text" class="form-control" id="editDescription" v-model="formData.roleDescription"
                               placeholder="请输入描述">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" @click="closeModal">取消</button>
                <button class="btn btn-primary" @click="saveData">保存</button>
            </div>
        </div>
    </div>

    <!-- 权限管理模态框 -->
    <div v-if="isPermissionModalVisible" class="modal-overlay" @click.self="closePermissionModal">
        <div class="modal" style="max-width: 800px;">
            <div class="modal-header">
                <h3>设置角色权限 - {{ permissionRoleName }}</h3>
                <button class="close-btn" @click="closePermissionModal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="permission-tree">
                    <ul v-for="menu in menuList" :key="menu.menuId">
                        <li>
                            <input type="checkbox" v-model="selectedPermissions" :value="menu.menuId" @change="toggleMenu(menu)">
                            <i class="fas folder-icon" :class="hasChildren(menu) ? 'fa-folder' : 'fa-file' "></i>
                            {{ menu.menuName }}
                            <ul v-if="hasChildren(menu)">
                                <li v-for="subMenu in menu.children" :key="subMenu.menuId">
                                    <input type="checkbox" v-model="selectedPermissions" :value="subMenu.menuId">
                                    <i class="fas page-icon fa-file"></i>
                                    {{ subMenu.menuName }}
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" @click="closePermissionModal">取消</button>
                <button class="btn btn-primary" @click="savePermissions">保存权限</button>
            </div>
        </div>
    </div>
</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>
<script>
    new Vue({
        el: '#app2',
        data: {
            searchForm: {
                roleName: '',
                roleDescription: ''
            },
            tableData: [],
            menuList: [], // 菜单列表，用于权限设置
            formData: {},
            isModalVisible: false,
            currentModalTitle: '',
            userName: '',

            // 权限管理相关
            isPermissionModalVisible: false,
            currentRoleId: '',
            permissionRoleName: '',
            selectedPermissions: [],

            // 分页相关数据
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            useFrontendPagination: false
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },
            // 当前页显示的数据
            paginatedData() {
                return this.tableData;
            },
            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码
                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }
                return pages;
            },
            // 当前页起始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },

            // 当前页结束索引
            endIndex() {
                const end = this.startIndex + this.pageSize;
                return Math.min(end, this.totalItems);
            }
        },
        methods: {
            search() {
                this.currentPage = 1; // 搜索时重置到第一页
                this.loadData();
            },
            // 统一使用带needReset参数的openModal方法
            openModal(title, needReset = true) {
                this.currentModalTitle = title;
                if (needReset) {
                    this.resetForm();
                }
                this.isModalVisible = true;
            },
            closeModal() {
                this.isModalVisible = false;
                this.resetForm();
            },
            resetForm() {
                this.formData = {};
            },
            // 修复后的handleEdit方法
            handleEdit(item) {
                // 先重置表单
                this.resetForm();

                // 使用setTimeout确保Vue响应式系统能正确处理
                setTimeout(() => {
                    // 单独赋值每个属性，确保Vue能检测到变化
                    this.$set(this.formData, 'roleId', item.roleId);
                    this.$set(this.formData, 'roleName', item.roleName);
                    this.$set(this.formData, 'roleDescription', item.roleDescription);
                    this.$set(this.formData, 'updateTime', item.updateTime || item.createTime);
                    // 添加状态字段赋值
                    this.$set(this.formData, 'status', item.status !== undefined ? item.status : 1); // 默认启用

                    // 传递needReset=false，防止formData被再次清空
                    this.openModal('编辑角色', false);
                }, 0);
            },
            handleDelete(roleId) {
                if (confirm('确定要删除该角色吗？删除后相关用户权限将受到影响！')) {
                    axios.delete(`/admin/role_manage/delete/${roleId}`)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('删除成功');
                                this.loadData(); // 重新加载数据
                            } else {
                                alert('删除失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('删除请求失败:', error);
                            alert('删除失败，请重试');
                        });
                }
            },
            saveData() {
                if (!this.formData.roleName) {
                    alert('请填写必填字段');
                    return;
                }
                const url = this.formData.roleId ? '/admin/role_manage/update' : '/admin/role_manage/add';
                axios.post(url, this.formData)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert(this.formData.roleId ? '编辑成功' : '添加成功');
                            this.closeModal();
                            this.loadData(); // 重新加载数据
                        } else {
                            alert(this.formData.roleId ? '编辑失败: ' : '添加失败: ' + resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('保存请求失败:', error);
                        alert('操作失败，请重试');
                    });
            },
            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                this.currentPage = page;
                this.loadData();
            },

            loadData() {
                axios.get("/admin/role_manage/getList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        roleName: this.searchForm.roleName || null,
                        roleDescription: this.searchForm.roleDescription || null
                    }
                })
                    .then(resp => {
                        if (resp.data.code === 200) {
                            this.tableData = resp.data.data.list || [];
                            this.totalItems = resp.data.data.total || 0;
                        } else {
                            alert("加载数据失败: " + resp.message);
                            this.tableData = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error('加载数据失败:', error);
                        alert('加载数据失败，请重试');
                    });
            },

            // 权限管理相关方法
            handlePermission(item) {
                this.currentRoleId = item.roleId;
                this.permissionRoleName = item.roleName;
                // 先加载菜单列表，然后在其回调中加载角色权限
                this.loadMenuList().then(() => {
                    this.loadRolePermissions();
                    this.isPermissionModalVisible = true;
                });
            },

            // 保留这个返回Promise的版本
            loadMenuList() {
                return new Promise((resolve, reject) => {
                    axios.get("/admin/menu_manage/getAllMenus")
                        .then(resp => {
                            if (resp.data.code === 200) {
                                this.menuList = resp.data.data || [];
                                resolve();
                            } else {
                                alert("加载菜单列表失败: " + resp.message);
                                this.menuList = [];
                                resolve();
                            }
                        })
                        .catch(error => {
                            console.error('加载菜单列表失败:', error);
                            alert('加载菜单列表失败，请重试');
                            resolve(); // 即使失败也resolve，确保流程继续
                        });
                });
            },

            closePermissionModal() {
                this.isPermissionModalVisible = false;
                this.currentRoleId = '';
                this.permissionRoleName = '';
                this.selectedPermissions = [];
            },

            // loadRolePermissions方法保持不变
            loadRolePermissions() {
                axios.get("/admin/role_manage/getRolePermissions", {
                    params: {roleId: this.currentRoleId}
                })
                    .then(resp => {
                        if (resp.data.code === 200) {
                            this.selectedPermissions = resp.data.data || [];
                            // 添加一个延迟来确保Vue正确更新视图
                            this.$nextTick(() => {
                                // 强制重新渲染（如果需要）
                                this.$forceUpdate();
                            });
                        } else {
                            alert("加载角色权限失败: " + resp.message);
                            this.selectedPermissions = [];
                        }
                    })
                    .catch(error => {
                        console.error('加载角色权限失败:', error);
                    });
            },

            // 修改保存权限方法，将roleId作为URL路径参数
            savePermissions() {
                axios.post(`/admin/role_manage/saveRolePermissions/${this.currentRoleId}`,
                    this.selectedPermissions
                )
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert('权限设置成功');
                            this.closePermissionModal();
                        } else {
                            alert('权限设置失败: ' + resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('保存权限失败:', error);
                        alert('权限设置失败，请重试');
                    });
            },

            toggleMenu(menu) {
                if (this.hasChildren(menu)) {
                    const menuId = menu.menuId;
                    const isChecked = this.selectedPermissions.includes(menuId);

                    menu.children.forEach(child => {
                        const index = this.selectedPermissions.indexOf(child.menuId);
                        if (isChecked && index === -1) {
                            this.selectedPermissions.push(child.menuId);
                        } else if (!isChecked && index !== -1) {
                            this.selectedPermissions.splice(index, 1);
                        }
                    });
                }
            },

            hasChildren(menu) {
                return menu.children && menu.children.length > 0;
            },

            formatDateTime(dateTime) {
                if (!dateTime) return '';
                const date = new Date(dateTime);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
        },
        mounted() {
            // 加载角色列表
            this.loadData();
            // 设置当前页面标识
            sessionStorage.setItem('currentPage', 'role_manage.html');
        }
    });
</script>
</body>
</html>
<style>
    .status-active {
        color: green;
        font-weight: bold;
    }

    .status-inactive {
        color: red;
        font-weight: bold;
    }
</style>
